import {
	gbs
} from 'config/';
import { Subject } from 'rxjs/Rx';

const chapterSubject = new Subject();
export default {
	name: 'editbook',
	components: {},
	data() {
		return {
			fields: [{
				key: 'question',
				desc: '请输入问题',
				label: '问题'
			}, {
				key: 'paragraph',
				desc: '请输入段落内容',
				type: 'textarea',
				label: '段落内容'
			}, {
				key: 'chapter_id',
				text: 'chapter_title',
				type: 'searchselect',
				subject: chapterSubject,
				list: [],
				desc: '请选择章节',
				label: '搜索章节',
				remoteMethod: function (query) {
					window.vue_$.$$api_common_chapter({
						data: query,
						fn: data => {
							let list = [];
							if (data && data.length) {
								for (let chapter of data) {
									list.push({
										value: chapter.id,
										text: chapter.get('title')
									})
								}
								this.list = list;
							} else {
								this.list = [];
							}
						}
					});
				}
			}, {
				key: 'question_index',
				desc: '请输入问题位置',
				label: '问题位置',
				type: 'inputnumber'
			}],
			default_value: {
				question: '',
				paragraph: '',
				question_index: 1,
				chapter_id: '',
				chapter_title: ''
			},
			rules: {
				question: [{
					required: true, message: '请输入内容', trigger: 'blur'
				}],
				paragraph: [{
					required: true, message: '请输入段落', trigger: 'blur'
				}],
			}
		}
	},
	methods: {
		onSubmit({ data, info }) {
			console.log(data, info);
			//如果没有任何文本text，就检测html中是否包含图片img，iframe,如果都没有，代表真的没有数据。
			let param = data;
			if (this.$route.query.id) {
				this.$$api_question_update({
					data: {
						data: param,
						obj: this.parseObj
					},
					fn: () => {
						this.$router.push('/main/question/list');
					}
				});
			} else {
				this.$$api_question_create({
					data,
					fn: () => {
						this.$router.push('/main/question/list');
					}
				});
			}
		}
	},
	created() {
	},
	mounted() {
		setTimeout(() => {
			if (this.$route.query.id) {
				var data = this.$route.query.id;
				this.$$api_question_find({
					data,
					fn: data => {
						chapterSubject.next([{ value: data.chapter_id, text: data.chapter_title }]);
						this.default_value.id = data.id;
						this.default_value.question = data.question;
						this.default_value.paragraph = data.paragraph;
						this.default_value.question_index = data.question_index;
						this.default_value.chapter_id = data.chapter_id;
						this.default_value.chapter_title = data.chapter_title;
					}
				});
			}
			if (this.$route.query.chapter_id) {
				this.$$api_common_chapter({
					data: { id: this.$route.query.chapter_id },
					fn: data => {
						console.log('data::::', data);
						chapterSubject.next([{ value: data[0].id, text: data[0].get('title') }]);
						this.default_value.chapter_id = data[0].id;
						this.default_value.chapter_title = data[0].get('title');
					}
				});
			}

		})
	},
	watch: {
		default_value: {
			deep: true,
			handler(v) {
				this.default_value = v;
			}
		}
	}
}